//
//  NetWorkHandle.m
//  YouWoYou
//
//  Created by dlios on 15-3-23.
//  Copyright (c) 2015年 lanou3g.com 蓝欧科技. All rights reserved.
//

#import "NetWorkHandle.h"
#import "AFNetworking.h"

@implementation NetWorkHandle
+ (void)getDataWithUrl:(NSString *)str completion:(void (^)(NSData *))block
{
    
    // 确定地址
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    //
    NSString *path = [NSString stringWithFormat:@"%@/%ld.aa", docPath, [str hash]];
    NSLog(@"%@", path);
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [manager GET:str parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
       
        NSLog(@"请求成功");
        
        NSString *requsetTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requsetTmp dataUsingEncoding:NSUTF8StringEncoding]];
        
       

        [resData writeToFile:path atomically:YES];
            block(resData);
       
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"请求失败");
        NSData *pickData = [NSData dataWithContentsOfFile:path];
        block(pickData);
    }];
}
+ (void)postDataWithUrl:(NSString *)str completion:(void(^)(NSData *data))block
{
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    //
    NSString *path = [NSString stringWithFormat:@"%@/%ld.aa", docPath, [str hash]];
    NSLog(@"%@", path);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
   
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];

    
    [manager POST:str parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        NSString *requsetTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requsetTmp dataUsingEncoding:NSUTF8StringEncoding]];
        
        
        
        [resData writeToFile:path atomically:YES];
        block(resData);

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求失败");
        NSData *pickData = [NSData dataWithContentsOfFile:path];
        block(pickData);
        
    }];

    
}

@end
